package org.dallasrowing.logbook.ui.view;

import org.dallasrowing.model.Boat;
import org.dallasrowing.model.Rower;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;

public class SWTAdminWindow implements AdminWindow {

	public class PasswordDialog extends Dialog {

		private Text password;
		private Button okButton;
		private String result = "";

		public PasswordDialog(Shell parent) {
			super(parent, 0);
		}

		public String show() {
			Shell parent = getParent();
			final Shell shell = new Shell(parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
			shell.setText("Enter Password:");
			shell.setLayout(new FillLayout(SWT.VERTICAL));
			shell.setMinimumSize(200, 20);
			password = new Text(shell, SWT.BORDER);
			password.setEchoChar('*');
			okButton = new Button(shell, SWT.PUSH | SWT.Activate);
			okButton.setText("OK");
			okButton.addListener(SWT.Selection, new Listener() {

				public void handleEvent(Event arg0) {
					result = password.getText();
					shell.dispose();
				}
			});
			shell.pack();
			shell.open();
			while(!shell.isDisposed())
			{
				if(!parent.getDisplay().readAndDispatch())
					parent.getDisplay().sleep();
			}
			return result;
		} 

	}

	private Shell dialog;
	private SwtRowerEditorWidget rowerWidget;
	private SwtBoatEditorWidget boatEditorWidget;

	public SWTAdminWindow(Shell parent) {
		dialog = new Shell (parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL |SWT.RESIZE);
		dialog.setText ("Edit Logbook data...");
		dialog.setLayout(new FillLayout());
		createMainPanel();
	}

	private void createMainPanel() {
		TabFolder tabFolder = new TabFolder(dialog, SWT.BORDER | SWT.FILL);
		createRowersPanel(tabFolder);
		createBoatsPanel(tabFolder);
	}

	private void createRowersPanel(TabFolder tabFolder) {
		TabItem rowersPanel = new TabItem(tabFolder, SWT.NONE );
		rowersPanel.setText("Rowers");
		rowerWidget = new SwtRowerEditorWidget(tabFolder);
		rowersPanel.setControl(rowerWidget);
	}

	private void createBoatsPanel(TabFolder tabFolder) {
		TabItem boatsPanel = new TabItem(tabFolder, SWT.NONE );
		boatsPanel.setText("Boats");
		boatEditorWidget = new SwtBoatEditorWidget(tabFolder);
		boatsPanel.setControl(boatEditorWidget );
	}


	public void show() {
		dialog.pack();
		dialog.open();
	}

	public BeanEditorWidget<Rower> getRowerEditorWidget() {
		return this.rowerWidget;
	}

	public void close() {
		dialog.close();
	}

	public BeanEditorWidget<Boat> getBoatEditorWidget() {
		return boatEditorWidget;
	}

	public String askPassword() {
		PasswordDialog d = new PasswordDialog(dialog);
		return d.show();
	}

}
